import { ref, watch } from "vue";
import {
  batchSaveProjectItem,
  cleanAllProjectItem,
  createProjectItem,
  deleteProjectItem,
  queryProject,
  queryProjectItemList,
  saveAllItemSorts,
  sortAllProjectItem,
  stopPublishFormRequest,
  updateProject,
  updateProjectItem
} from "@/views/formgen/api";
import { useFormInfo } from "@/stores/formInfo";
import { cloneDeep, debounce, toLower } from "lodash-es";
import { ElMessageBox } from "element-plus";
import { dbDataConvertForItemJson, formItemConvertData } from "@/views/formgen/utils/convert";
import { i18n } from "@/i18n";
import {
  FormActiveType,
  FormConfType,
  FormDrawingItem,
  LocaleConfig
} from "@/views/formgen/components/FormDesign/types";
import { operationHistory } from "@/views/formgen/components/FormDesign/hooks/useOperationHistory";
import { useDebounceFn } from "@vueuse/core";
import {
  convertLangContent,
  getFormLangContent,
  parseLangContent,
  tempLangContent
} from "@/views/formgen/utils/formI18n";

/**
 * 表单设计Hook
 */

export function useFormDesign() {
  const { setCurrentFormName, setIsSaving, setFormType } = useFormInfo();
  // 全部题目
  const drawingList = ref<FormDrawingItem[]>([]);
  // 表单信息
  const formConf = ref<FormConfType | null>({
    description: "",
    formKey: null,
    labelPosition: undefined,
    labelWidth: 0,
    status: 1,
    title: "",
    type: 1
  });

  // 多语言配置
  const localeConfig = ref<LocaleConfig>({
    langCodes: [],
    defaultLang: ""
  });

  const langContent = ref<any>({});

  const currentLanguage = ref("");

  // 选中id
  const activeIndex = ref<number>(-1);
  // 选中题目
  const activeData = ref<FormActiveType | null>(null);

  /**
   * 是否显示已经发布了的弹窗
   */
  const showPublishConfirm = ref<boolean>(false);

  const formKey = ref<string>("");
  const { execute } = operationHistory;

  // 是否是默认表单编辑器状态 是的话增删改单独走表单的接口
  const isDefaultApi = ref<boolean>(true);

  /**
   * 克隆组件
   * @param origin 元数据
   * @param labelBold 是否加粗
   * @param index 下标 批量的时候避免id重复
   */
  const cloneComponent = (origin: any, labelBold = true, index = 1) => {
    const clone = cloneDeep(origin);
    createIdAndKey(clone, index);
    if (clone.action) {
      clone.action += formKey.value;
    }
    console.log(clone.typeId);
    if (clone.typeId !== "SUB_FORM" && labelBold) {
      clone.config.label = `<strong><span style="font-size: var(--form-theme-labelFontSize, 14px);" >${clone.config.label}</span></strong>`;
    }
    return clone;
  };

  const createIdAndKey = (item: any, i = 0) => {
    const config = item.config;
    // 题目id 批量生成时传入i避免重复
    config.formId = `${toLower(item.typeId)}${new Date().getTime() + i}`;
    // 渲染key 在部分组件无法动态更新 强制更新
    config.renderKey = `${config.formId}${+new Date()}`;
    item.vModel = config.formId;
    return item;
  };

  // 如果选中了某个子表单
  const activeSubformItem = ref<FormDrawingItem | null>(null);

  const activeFormItem = (currentItem: FormDrawingItem, index: number, parentItem?: FormDrawingItem) => {
    activeData.value = currentItem;
    // 说明是被选中的子表单组件
    if (parentItem) {
      activeSubformItem.value = parentItem;
    }
    activeIndex.value = index;
  };

  const copyDrawingItem = (item: any) => {
    checkFormPublishStatus().then((result: boolean) => {
      if (result) {
        execute(drawingList.value);
        const clone = cloneDeep(item);
        createIdAndKey(clone);
        // 数组指定位置1插入 找到原来的位置
        const index = drawingList.value.findIndex((val: any) => val.config.formId === item.config.formId);
        drawingList.value.splice(index + 1, 0, clone);
        activeFormItem(clone, index + 1);
        createProjectItem(formItemConvertData(clone, formKey.value)).then(() => {});
      }
    });
  };

  const deleteDrawingItem = async (item: any) => {
    let isSuccess = true;
    if (isDefaultApi.value) {
      isSuccess = await deleteProjectItemInfo(item);
    }
    if (isSuccess) {
      execute(drawingList.value);
      const index = drawingList.value.findIndex((val: any) => val.config.formId === item.config.formId);
      drawingList.value.splice(index, 1);
      const len = drawingList.value.length;
      if (len) {
        activeFormItem(drawingList.value[len - 1], len - 1);
      }
    }
  };

  const queryProjectInfo = async () => {
    const res = await queryProject(formKey.value);
    formConf.value!.status = res.data.status;
    formConf.value!.type = res.data.type;
    // 多语言配置
    localeConfig.value = res.data?.localeConfig || {};
    // 一键翻译完成后会改变currentLanguage的值 这里需要兼容下
    currentLanguage.value = currentLanguage.value || res.data?.localeConfig?.defaultLang || "zh-CN";
    langContent.value = res.data?.langContent || {};
    const title = getFormLangContent(currentLanguage.value, "name", langContent.value) || res.data.name;
    if (title) {
      formConf.value!.title = title;
    }
    const description = getFormLangContent(currentLanguage.value, "description", langContent.value) || res.data.description;
    if (description) {
      formConf.value!.description = description;
    }
    setFormType(res.data.type);
    setCurrentFormName(formConf.value!.title);
  };

  /**
   * 更新标题和描述
   */
  const saveProjectInfo = () => {
    setCurrentFormName(formConf.value!.title);
    // 更新多语言配置
    langContent.value[currentLanguage.value] = {
      name: formConf.value!.title,
      description: formConf.value!.description
    };
    // 用默认的语言更新 不然最后编辑那个语言就变成了哪个语言
    const title = getFormLangContent(localeConfig.value.defaultLang, "name", langContent.value);
    const description = getFormLangContent(localeConfig.value.defaultLang, "description", langContent.value);
    updateProject({
      formKey: formKey.value,
      name: title || formConf.value!.title,
      description: description || formConf.value!.description,
      langContent: langContent.value
    }).then(() => {});
  };

  // 控制是否能新增组件
  const isAllowAdd = ref(false);

  /**
   * 是否发布
   * @return true 发布了 false没发布
   */
  const checkFormPublishStatus = async () => {
    console.log(isAllowAdd.value);
    if (!isDefaultApi.value) {
      return isAllowAdd.value;
    }
    let noPublish = true;
    if (formConf.value!.status === 2 && !showPublishConfirm.value) {
      noPublish = false;
      showPublishConfirm.value = true;
      try {
        await ElMessageBox.confirm(i18n.global.t("form.form.isEdit"), i18n.global.t("formI18n.all.waring"), {
          confirmButtonText: i18n.global.t("formI18n.all.confirm"),
          cancelButtonText: i18n.global.t("formI18n.all.cancel"),
          buttonSize: "default"
        });
        await stopPublishFormRequest({ formKey: formKey.value });
        await queryProjectInfo();
        noPublish = true;
      } catch (error) {
        noPublish = false;
      } finally {
        showPublishConfirm.value = false;
      }
    }

    return noPublish;
  };

  /**
   * 更新题目
   */
  const updateProjectItemInfo = debounce(async (val: any) => {
    if (!isDefaultApi.value) {
      return true;
    }
    setIsSaving(true);
    const data = formItemConvertData(val, formKey.value, currentLanguage.value, localeConfig.value.defaultLang);
    await updateProjectItem(data);
    setIsSaving(false);
  });

  /**
   * 删除题目
   * @param val
   */
  const deleteProjectItemInfo = async (val: any) => {
    if (!isDefaultApi.value) {
      return true;
    }
    setIsSaving(true);
    const data = formItemConvertData(val, formKey.value);
    try {
      await deleteProjectItem(data);
      syncAllItemSorts();
      return true;
    } catch (e) {
      return false;
    } finally {
      setIsSaving(false);
    }
  };

  /**
   * 保存题目
   * @param item
   */
  const saveProjectItemInfo = async (item: any) => {
    if (!isDefaultApi.value) {
      return true;
    }
    setIsSaving(true);
    let isSuccess = false;
    const params = formItemConvertData(item, formKey.value);
    // const pItem = item;

    await createProjectItem(params).then(() => {
      setIsSaving(false);
      // 后端统一控制顺序 不在使用 2025-3-26
      // pItem.sort = res.data.sort;
      isSuccess = true;
    });
    syncAllItemSorts();
    // 如果是分页组件 刷新所有分页的页码
    if (item.typeId === "PAGINATION") {
      updatePaginationList();
    }
    return isSuccess;
  };

  /**
   *  更新分页的信息
   */
  const updatePaginationList = () => {
    const { length } = drawingList.value.filter((item: any) => item.typeId === "PAGINATION");
    let curr = 1;
    drawingList.value.forEach((item: any, index: any) => {
      if (item.typeId === "PAGINATION") {
        item.totalPageNum = length;
        item.currPageNum = curr++;
        drawingList.value[index] = item;
      }
    });
  };

  /**
   * 查询全部题目
   */
  const queryProjectItems = async () => {
    const res = await queryProjectItemList({ key: formKey.value });
    drawingList.value = res.data.map((item: any) => {
      // 如果没有多语言配置 说明是旧数据 给他初始化一个
      if (!item.scheme.langContent && currentLanguage.value) {
        let currentItemLangContent: Record<string, any> = {};
        currentItemLangContent[currentLanguage.value] = convertLangContent(item, currentLanguage.value);
        // 更新到题目
        item.langContent = currentItemLangContent;
        // 更新到临时缓存
        tempLangContent[item.formItemId] = currentItemLangContent;
      }
      // 初始化完成 转换为elementui需要的json
      return dbDataConvertForItemJson(item, currentLanguage.value);
    });
    // 更新分页
    updatePaginationList();
  };

  // 同步全部题目
  const syncAllItem = useDebounceFn(() => {
    if (!isDefaultApi.value) {
      return;
    }
    setIsSaving(true);
    batchSaveProjectItem({
      formKey: formKey.value,
      list: drawingList.value.map((item: any) => {
        return formItemConvertData(item, formKey.value);
      })
    }).then(() => {
      setIsSaving(true);
      syncAllItemSorts();
    });
  }, 4000);

  // 保存所有题目的顺序
  const syncAllItemSorts = useDebounceFn(() => {
    if (!isDefaultApi.value) {
      return;
    }
    setIsSaving(true);
    saveAllItemSorts({
      formKey: formKey.value,
      sortIdList: drawingList.value.map((item: any) => {
        return item.config.formId;
      })
    }).then(() => {
      setIsSaving(false);
    });
  }, 1000);

  // 刷新所有的题目顺序到数据库
  const refreshAllItemSorts = () => {
    if (!isDefaultApi.value) {
      return;
    }
    sortAllProjectItem({ formKey: formKey.value });
  };

  // 清空全部题目
  const cleanDrawingItem = async () => {
    ElMessageBox.confirm(i18n.global.t("formgen.index.cleanAll"), {
      buttonSize: "default"
    })
      .then(() => {
        drawingList.value = [];
        if (isDefaultApi.value) {
          cleanAllProjectItem({
            formKey: formKey.value
          });
        }
      })
      .catch(() => {});
  };

  const loadData = async () => {
    await queryProjectInfo();
    await queryProjectItems();
  };

  watch(
    () => currentLanguage.value,
    (lang: string) => {
      activeData.value = null;
      activeIndex.value = -1;
      const title = getFormLangContent(lang, "name", langContent.value);
      if (title) {
        formConf.value!.title = title;
      }
      const description = getFormLangContent(lang, "description", langContent.value);
      if (description) {
        formConf.value!.description = description;
      }
      // 更新题目
      drawingList.value.forEach((item: any) => {
        // 因为数据是在提交的时候转换的 所以在没刷新前这个item里面得多语言配置是旧的 drawingList里面的值没有刷新
        // 如果提交的时候修改item就会导致重复触发提交 不是很好判断 这里我们也兼容下 如果临时的里面有说明修改过了 这里用本地临时的
        parseLangContent(item, lang, tempLangContent[item.config!.formId] || item.langContent);
      });
    }
  );

  return {
    queryProjectInfo,
    saveProjectInfo,
    updateProjectItemInfo,
    deleteProjectItemInfo,
    saveProjectItemInfo,
    updatePaginationList,
    queryProjectItems,
    formConf,
    drawingList,
    activeIndex,
    activeData,
    showPublishConfirm,
    formKey,
    copyDrawingItem,
    loadData,
    deleteDrawingItem,
    activeFormItem,
    cloneComponent,
    isDefaultApi,
    checkFormPublishStatus,
    createIdAndKey,
    syncAllItem,
    syncAllItemSorts,
    refreshAllItemSorts,
    cleanDrawingItem,
    isAllowAdd,
    activeSubformItem,
    localeConfig,
    currentLanguage
  };
}

export const formDesign = useFormDesign();
